/*
 * 
 */

package com.memorytech.starchive;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import jp.co.memory_tech.starchive.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.memorytech.starchive.dialog.BarcodeConfirmDialogFragment;
import com.memorytech.starchive.entity.BarcodeInfo;
import com.memorytech.starchive.entity.HistoryBarcode;
import com.memorytech.starchive.interfaceclass.BarcodeReaderInfo;
import com.memorytech.starchive.interfaceclass.OnHistoryBarcodeListener;
import com.memorytech.starchive.utils.SaveData;
import com.memorytech.starchive.xmlparser.BarcodeParser;

// TODO: Auto-generated Javadoc
/**
 * The Class HistoryActivity.
 * 
 * @author Tam-LT
 */
public class HistoryActivity extends FragmentActivity implements
        OnClickListener, OnHistoryBarcodeListener {

    /**
     * Called when the activity is first created.
     * 
     * @param savedInstanceState the saved instance state
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history_fragment);
        TextView textView = (TextView) findViewById(R.id.title);
        textView.setText(getString(R.string.history));
        findViewById(R.id.history_search).setOnClickListener(this);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first
        // fragment
        if (findViewById(R.id.history_fragment_container) != null) {

            Log.i("Tamle", "the case og small size screen");

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                Log.i("Tamle", "return");
                return;
            }

            // Create an instance of HistoryListProduct
            HistoryListProduct firstFragment = new HistoryListProduct();

            // In case this activity was started with special instructions from
            // an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.history_fragment_container, firstFragment).commit();
        }
    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Log.i("tamle", "back pressed");
        super.onBackPressed();
    }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.history_search:

                String searchInfo = ((EditText) findViewById(R.id.history_search_field)).getText()
                        .toString().trim();
                if (searchInfo.equals("")) {
                    BarcodeConfirmDialogFragment.show(this,
                            "Please enter search information");
                } else {
                    Log.i("Tamle", "History search button clicked");

                }

                break;

            default:
                break;
        }

    }

    /*
     * (non-Javadoc)
     * @see com.arisvn.barcode.Interface.OnHistoryBarcodeListener#
     * onHistoryBarcodeSelected(com.arisvn.barcode.Entity.HistoryBarcode)
     */
    @Override
    public void onHistoryBarcodeSelected(HistoryBarcode historyBarcode) {
        // TODO Auto-generated method stub

        // Capture the HistoryProductDetail fragment from the activity layout
        BarcodeInfo barcodeInfo = null;
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            XMLReader xr = sp.getXMLReader();

            BarcodeParser dataHandler = new BarcodeParser();
            xr.setContentHandler(dataHandler);
            // InputStream inputStream =
            // getActivity().getAssets().open("sample.xml");
            // xr.parse(new InputSource(inputStream));

            String hostname = SaveData.getInstance(getApplicationContext()).gethostname();
            Log.i("Tamle", "hostname is: " + hostname);

            if (hostname.length() > 0) {
                String request_url = String.format(
                        "http://%s/StarchiveWebInterface/index.php/GetInformation", hostname);
                Log.i("Tamle", "request url is: " + request_url);
                xr.parse(new InputSource(
                        new FileInputStream(
                                getDataSource(request_url))));
                barcodeInfo = dataHandler.getData();
                // barcodeInfo = dataHandler.getData();
            }

        } catch (ParserConfigurationException pce) {
            Log.e("SAX XML", "sax parse error", pce);
            barcodeInfo = null;
        } catch (SAXException se) {
            Log.e("SAX XML", "sax error", se);
            barcodeInfo = null;
        } catch (IOException ioe) {
            Log.e("SAX XML", "sax parse io error", ioe);
            barcodeInfo = null;
        }
        if (barcodeInfo == null) {
            return;
        }
        HistoryProductDetail productDetail = (HistoryProductDetail)
                getSupportFragmentManager().findFragmentById(R.id.history_detail_fragment);
        HistoryBarcode barcode = new HistoryBarcode();
        try {
            barcode.setFreeSpace(Float.parseFloat(barcodeInfo.getMedium().getFreeSpace()));
            barcode.setUsedSpace((Float.parseFloat(barcodeInfo.getMedium().getTotalSpace()) - Float
                    .parseFloat(barcodeInfo.getMedium().getFreeSpace())));

            if (productDetail != null) {
                // If HistoryProductDetail frag is available, we're in two-pane
                // layout...

                // Call a method in the HistoryProductDetail to update its
                // content
                productDetail.updateProductDetail(barcode);

            } else {
                // If the frag is not available, we're in the one-pane layout
                // and
                // must swap frags...

                // Create fragment and give it an argument for the selected
                // HistoryProduct
                HistoryProductDetail newFragment = new HistoryProductDetail();
                Bundle args = new Bundle();
                args.putSerializable(HistoryProductDetail.HISTORY_BARCODE, barcode);
                newFragment.setArguments(args);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this
                // fragment,
                // and add the transaction to the back stack so the user can
                // navigate back
                transaction.replace(R.id.history_fragment_container, newFragment);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit();
            }
        } catch (NumberFormatException e) {
            // TODO: handle exception
            Log.i("Tamle", "error: " + e.toString());
        }

    }

    @Override
    public void onDetailItemSelected(HistoryBarcode historyBarcode) {
        // TODO Auto-generated method stub
        // HistoryProductDetail productDetail = (HistoryProductDetail)
        // getSupportFragmentManager().findFragmentById(R.id.history_detail_fragment);
        //
        // if (productDetail != null) {
        //
        // productDetail.setHistoryBarcode(historyBarcode);
        //
        // }
        // //
        Activity activity = getParent();
        // I'm assuming were inside an Activity which is started by TabActivity
        if (activity instanceof MainActivity) {
            MainActivity ta = (MainActivity) activity;
            // // now determine the Tab you wanna start
            ta.changeTab(BarcodeReaderInfo.SEARCH, historyBarcode.getBarcode());

        }

    }

    public void onClearCache() {
        // TODO Auto-generated method stub
        HistoryProductDetail productDetail = (HistoryProductDetail)
                getSupportFragmentManager().findFragmentById(R.id.history_detail_fragment);
        if (productDetail != null) {
            productDetail.updateProductDetail(null);
            productDetail.setHistoryBarcode(null);
        }
    }

    private String getDataSource(String path) throws IOException {
        if (!URLUtil.isNetworkUrl(path)) {
            return path;
        } else {
            URL url = new URL(path);
            URLConnection cn = url.openConnection();
            cn.connect();
            InputStream stream = cn.getInputStream();
            if (stream == null)
                throw new RuntimeException("stream is null");
            File temp = File.createTempFile("mediaplayertmp", ".dat");
            temp.deleteOnExit();
            String tempPath = temp.getAbsolutePath();
            FileOutputStream out = new FileOutputStream(temp);
            byte buf[] = new byte[128];
            do {
                int numread = stream.read(buf);
                if (numread <= 0)
                    break;
                out.write(buf, 0, numread);
                Log.i("TamLe", "write sample.xml to sdcard");
            } while (true);
            try {
                stream.close();
            } catch (IOException ex) {
                Log.e("Tamle", "error: " + ex.getMessage(), ex);
            }
            return tempPath;
        }
    }
}
